import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:znmm/config/app_color.dart';
import 'package:intl/intl.dart';
import 'package:logger/logger.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../config/app_asset.dart';
export 'dart:io';
export 'dart:math';
export 'dart:convert';

typedef CompareSetFunc = int Function(dynamic a, dynamic b);
var logger = Logger();
final GlobalKey<NavigatorState> gloNavigatorKey = GlobalKey<NavigatorState>();

//比较宽松的邮箱正则表达式
final RegExp globalEmailRegex = RegExp(
  r'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$',
);
//手机号码正则表达式
final RegExp globalPhoneRegex = RegExp(
    r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');

class MyGlobal {
  static double screenWidth = 0;
  static double screenHeight = 0;
  static double paddingTop = 0; //刘海高度
  static double paddingBottom = 0; //底部刘海高度
  static double bottomNavHeight = 48; //底部按钮高度
  static Timer? _loadingTime;

  static bool init(BuildContext context) {
    MediaQueryData queryData = MediaQuery.of(context);
    screenWidth = queryData.size.width;
    screenHeight = queryData.size.height;
    paddingTop = queryData.padding.top;
    paddingBottom = queryData.padding.bottom;

    return true;
  }

  //通用导航栏
  static PreferredSizeWidget getNavigationBar(
    BuildContext context,
    String strTitle, {
    Widget? backWidget,
    bool bIsBack = true, //是否需要返回
    List<Widget>? actions,
    Widget? title,
  }) {
    backWidget ??= GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Navigator.maybePop(context);
        //Get.back();
      },
      child: const Icon(
        Icons.arrow_back, //arrow_back  arrow_back_ios
        color: Colors.black,
        size: 22,
      ),
    );

    return AppBar(
      //backgroundColor: color ?? Colors.blue,
      backgroundColor: AppColor.whiteColor,
      elevation: 0,
      centerTitle: true,
      leadingWidth: 80,
      leading: bIsBack ? backWidget : null,
      title: title ??
          Text(
            strTitle,
            style: TextStyle(color: AppColor.black, fontSize: 18),
          ),
      actions: actions,
    );
  }

  static void showInfo(String msg,
      {Toast timeLen = Toast.LENGTH_LONG, int itime = 1}) {
    Fluttertoast.showToast(
        msg: msg,
        gravity: ToastGravity.CENTER,
        toastLength: timeLen,
        //timeInSecForIosWeb: itime, // 设置时间为5秒
        textColor: Colors.white,
        backgroundColor: const Color.fromARGB(255, 51, 56, 62));
  }

  static void showWarning(String msg, {Toast timeLen = Toast.LENGTH_SHORT}) {
    Fluttertoast.showToast(
        msg: msg,
        gravity: ToastGravity.CENTER,
        toastLength: timeLen,
        textColor: Colors.white,
        backgroundColor: const Color.fromARGB(255, 51, 56, 62));
  }

  static void showError(String msg,
      {Toast timeLen = Toast.LENGTH_SHORT, int itime = 1}) {
    print("Error: $msg");

    Fluttertoast.showToast(
        gravity: ToastGravity.CENTER,
        msg: msg,
        toastLength: timeLen,
        timeInSecForIosWeb: itime, // 设置时间为5秒
        textColor: const Color(0xFFF5F6F9),
        backgroundColor: const Color(0xFF2B3039));
  }

  //dismissOnTap ： true允许加载中操作
  static void showLoading(
      {String msg = "loading...", bool dismissOnTap = false}) {
    if (_loadingTime != null) {
      _loadingTime?.cancel();
      _loadingTime = null;
    }

    if (dismissOnTap) {
      EasyLoading.show(
          status: msg,
          dismissOnTap: dismissOnTap,
          maskType: EasyLoadingMaskType.none);
    } else {
      EasyLoading.show(
          status: msg,
          dismissOnTap: dismissOnTap,
          maskType: EasyLoadingMaskType.clear);
    }
  }

  static void showLoadingTime(
      {String msg = "Loading...", bool dismissOnTap = false, int timeOut = 5}) {
    if (_loadingTime != null) {
      _loadingTime?.cancel();
      _loadingTime = null;
    }

    if (dismissOnTap) {
      EasyLoading.show(
          status: msg,
          dismissOnTap: dismissOnTap,
          maskType: EasyLoadingMaskType.none);
    } else {
      EasyLoading.show(
          status: msg,
          dismissOnTap: dismissOnTap,
          maskType: EasyLoadingMaskType.black);
    }
    var out = Duration(seconds: timeOut);
    // print('currentTime=' + DateTime.now().toString()); // 当前时间
    _loadingTime = Timer(out, () {
      //callback function
      // print('afterTimer=' + DateTime.now().toString()); // 5s之后
      MyGlobal.hideLoading();
    });
  }

  static void hideLoading() {
    if (_loadingTime != null) {
      _loadingTime?.cancel();
      _loadingTime = null;
    }

    EasyLoading.dismiss();
  }

  // ignore: non_constant_identifier_names
  static void ShowSuccess(String strContent) {
    EasyLoading.showSuccess(strContent);
  }

  //判断json返回字符串数据是否为null
  static String checkNullOrEmpty(String? value, {String strRetun = ""}) {
    if (value == null || value.isEmpty) {
      return strRetun;
    } else {
      return value;
    }
  }

  //判断json返回int double 数据是否为null
  static T checkNullOrZero<T extends num>(T? value) {
    if (value == null) {
      // 如果 T 是 double 类型，返回 0.0，否则返回 0
      return T == double ? 0.0 as T : 0 as T;
    } else {
      return value;
    }
  }

  //泛指类型
  static dynamic getDynamicValue(dynamic value) {
    if (value is int) {
      return value;
    } else if (value is double) {
      return value;
    }
    return 0;
  }

  //获取 N 个月前的今天 'yyyy-MM-dd'格式
  static String getPreviousMonthDate(int monthsToGoBack) {
    DateTime now = DateTime.now();
    DateTime previousMonth =
        DateTime(now.year, now.month - monthsToGoBack, now.day);

    // Handle edge cases for January and going back more than 12 months
    while (previousMonth.month <= 0) {
      previousMonth =
          DateTime(previousMonth.year - 1, previousMonth.month + 12, now.day);
    }

    String formattedDate = previousMonth.toLocal().toString().split(' ')[0];
    return formattedDate;
  }

  //格式转换 'yyyy-MM-dd' -> 'yyyyMMdd'
  static String convertDateFormat(String originalDate) {
    if (originalDate.isEmpty) {
      return "";
    }
    DateTime dateTime = DateFormat('yyyy-MM-dd').parseStrict(originalDate);
    String convertedDate = DateFormat('yyyyMMdd').format(dateTime);
    return convertedDate;
  }

  //获取当前日期传入你需要的格式'yyyy-MM-dd'
  static String getCurrentDate(String format) {
    DateTime currentDate = DateTime.now();
    String formattedDate = DateFormat(format).format(currentDate);
    return formattedDate;
  }

  static String convertToDateString(String dateTimeString,
      {String format = 'yyyy-MM-dd'}) {
    if (dateTimeString.isEmpty || format.isEmpty) {
      return "";
    }
    DateTime dateTime = DateTime.parse(dateTimeString);
    String dateString = DateFormat(format).format(dateTime);
    return dateString;
  }

  //判断是否为有效网址
  static bool isValidURL(String? url) {
    if (url == null || url.isEmpty) return false;
    String pattern =
        r'^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-zA-Z0-9]+([-.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\/.*)?$';
    RegExp regExp = RegExp(pattern);
    return regExp.hasMatch(url);
  }

  // 正则表达式来检查邮箱格式是否有效
  static bool isValidEmail(String email) {
    // 这个正则表达式可以匹配常见的邮箱格式
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');

    return emailRegex.hasMatch(email);
  }

  ///验证是否为域名
  static bool verifyDomain(String domain) {
    var result = false;
    RegExp domainExp = RegExp(
        r"^(|[a-zA-Z0-9].)[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,6}(\:[0-9]{1,5})*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&amp;%\$#\=~_\-@]+))*$");
    if (domainExp.hasMatch(domain)) {
      result = true;
    }
    return result;
  }

  // 1.校验邮箱
  static bool verifyEmail(String email) {
    String format = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
    bool isRight = RegExp(format).hasMatch(email);
    return isRight;
  }

  static Widget emptyWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.asset(
            width: 240,
            height: 260,
            AppAsset.empty,
            fit: BoxFit.contain,
          ),
          // Icon(
          //   Icons.shopping_cart_outlined,
          //   color: Colors.black.withOpacity(0.1),
          //   size: 1.sw / 2,
          // ),
          const Text(
            "NO DATA",
            style: TextStyle(
                fontSize: 18, fontWeight: FontWeight.w500, color: Colors.grey),
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }

  //翻译
  // static Future<String> translateToEnglish(String inputText) async {
  //   final translator = GoogleTranslator();
  //   Translation translation = await translator.translate(inputText, to: 'en');
  //   return translation.text;
  // }
}

///-----------------------权限申请工具，申请权限走这里

Future<bool> requestPermission(
  BuildContext context,
  Permission permission, {
  bool bHasDDialog = false,
}) async {
  var status = await permission.status;
  if (status.isDenied) {
    status = await permission.request();
    if (status.isPermanentlyDenied && bHasDDialog) {
      /// 用户永久拒绝，弹出确认对话框
      // ignore: use_build_context_synchronously
      final bool? confirm = await showDialog<bool>(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text("Unable to obtain current permissions"),
            content: const Text(
                "It may not work properly. Go to the app settings page to obtain permissions."),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false), // 取消
                child: const Text("Cancel"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true); // 确认
                },
                child: const Text("Go to Settings"),
              ),
            ],
          );
        },
      );

      if (confirm == true) {
        openAppSettings();
      }
    }
  }

  return status.isGranted;
}

// Future<bool> requestPermission(Permission permission,
//     {bool bHasDDialog = false}) async {
//   var status = await permission.status;
//   if (status.isDenied) {
//     status = await permission.request();
//     if (status.isPermanentlyDenied && bHasDDialog) {
//       /// 用户永久拒绝
//       await DialogUtil.showConfirmDialog(
//         titleText: "无法获取当前权限",
//         messageText: "可能无法正常使用，是否前往应用设置页获取权限",
//         onConfirm: () => openAppSettings(),
//       );
//     }
//   }

//   return status.isGranted;
// }

//open url
Future<void> onLaunchUrl(
  BuildContext context,
  Uri uri, {
  bool shouldShowDialog = true,
  LaunchMode mode = LaunchMode.externalApplication,
}) async {
  if (shouldShowDialog &&
      (mode != LaunchMode.inAppWebView && mode != LaunchMode.platformDefault)) {
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("An external program will be opened for you"),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false), // 取消
              child: const Text("Cancel"),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true), // 确认
              child: const Text("Confirm"),
            ),
          ],
        );
      },
    );

    if (confirm == true) {
      _launchUrl(uri, mode: mode);
    }
  } else {
    _launchUrl(uri, mode: mode);
  }
}

// Future onLaunchUrl(
//   Uri uri, {
//   LaunchMode mode = LaunchMode.externalApplication,
//   bool showDialog = true,
// }) async {
//   if (showDialog &&
//       (mode != LaunchMode.inAppWebView && mode != LaunchMode.platformDefault)) {
//     DialogUtil.showConfirmDialog(
//         titleText: "即将为您打开外部程序",
//         cancelText: "取消",
//         confirmText: "确认",
//         onConfirm: () async {
//           _launchUrl(uri, mode: mode);
//         });
//   } else {
//     _launchUrl(uri, mode: mode);
//   }
// }

Future _launchUrl(
  Uri uri, {
  LaunchMode mode = LaunchMode.externalApplication,
}) async {
  try {
    await launchUrl(uri, mode: mode);
  } catch (e) {
    MyGlobal.showInfo("Jump failed");
  }
}
